package com.wyiot.pet.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wyiot.pet.model.dto.UserDTO;
import com.wyiot.pet.model.entity.UserDO;
import com.wyiot.core.security.UserContext;
import com.wyiot.pet.service.UserService;
import com.wyiot.core.exception.ValidateException;
import com.wyiot.core.api.ValidateGroup;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 用户管理控制层
 *
 * @author yly
 * @since 2022年03月30日
 */
@RestController
public class UserController {
    @Resource
    UserService userService;

    /**
     * 用户注册
     *
     * @see UserDTO
     */
    @PostMapping("/user")
    public void userRegistration(@RequestBody @Validated({ValidateGroup.First.class}) UserDTO userDTO , BindingResult result) {
        userService.userRegistration(userDTO);
    }

    /**
     * 修改用戶類型
     *
     * @param userType 用户类型
     */
    @PutMapping("userType/{type}")
    public void updateUserType(@PathVariable("type") Integer userType){
        userService.update(Wrappers.lambdaUpdate(UserDO.class).eq(UserDO::getUserId , UserContext.getUserId()).set(UserDO::getUserType ,userType));
    }

    /**
     * 获取当前用户
     *
     * @param userId 用户id
     */
    @GetMapping("/user/{id}")
    public UserDO selectUser(@PathVariable("id") Long userId) {
        if (UserContext.getUserId()!=userId){
            throw ValidateException.of("非法请求");
        }
        return userService.getById(userId);
    }

}